package com.sn.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.sn.shop.dao.RedisDao;
import com.sn.shop.model.User;
import com.sn.shop.request.RequestLogin;
import com.sn.shop.utils.JwtUtil;
import com.sn.shop.utils.ReturnResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @auther sn
 * @date 2018/1/23
 * @description TODO
 */
@Api(value = "登陆", tags = "登陆")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    RedisDao redisDao;

    @ApiOperation(value = "登陆")
    @PostMapping("login")
    public ReturnResult login(@RequestBody RequestLogin params) throws IOException {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(params.getUsername(), params.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        User user = (User) authentication.getPrincipal();
        String token = JwtUtil.TOKEN_PREFIX + JwtUtil.generateToken(params.getUsername());
        // 把token写入redis
        redisDao.setKey(token, JSONObject.toJSONString(user));
        Map<String, Object> extra = new HashMap<>();
        extra.put(JwtUtil.TOKEN, token);
        return ReturnResult.success("登陆成功", extra);
    }


}
